package com.topteam.frame.controllor;

import com.topteam.application.TopApplicationContext;
import com.topteam.core.Path;
import com.topteam.frame.entity.FrameUser;
import com.topteam.security.UserSession;
import com.topteam.utility.CommUtil;
import com.topteam.utility.StringUtil;


@Path("/security")
public class SecurityController extends BaseController{

	/**
	 * 打开登录页面的时候，对 UserSession 和 Cookie 验证是否已经登录，如果已经登录直接到首页或者回调页面
	 */
	public void login(){
		boolean succ = false;
		String msg = getPara("msg");
		if(msg!=null && msg.equals("1"))
			msg = "用户名或密码不能为空";
		if(msg!=null && msg.equals("2"))
			msg = "用户名不存在或密码错误";
		setAttr("msg", StringUtil.isNull(msg)?"1":msg);
		String callbackUrl = getPara("callback")==null?"/index":getPara("callback");
		UserSession session = getSessionAttr("userSession");
		if(session!=null){
			succ = true;
		}else{
			TopApplicationContext applicationContext = TopApplicationContext.getInstance();
			String cookieLogin = applicationContext.getValue("cookieLogin");
			if(cookieLogin!=null&&cookieLogin.equals("true")){
				String username = getCookie("username");
				String password = getCookie("password");
				FrameUser u = FrameUser.dao.getUserByUserName(username);
				
				// cookie 中存放的密码应该为加密后的
				if(u.get("password").equals(password)){
					succ = true;
				}
			}
			
		}
		
		if(succ){
			redirect(callbackUrl);
		}else{
			render("/login.html");
		}
	}
	
	/**
	 * 登录验证方法
	 */
	public void auth(){
		String username = getPara("username");
		String password = getPara("password");
		String callbackUrl = getPara("callback") == null ? "/index" :  getPara("callback");
		if(username==null || username.equals("")){
			setAttr("callback", callbackUrl);
			redirect("/security/login?msg=1");
			return;
		}
		FrameUser u = FrameUser.dao.getUserByUserName(username);
		if(u!=null&&CommUtil.md5(password).equals(u.get("password"))){
			//验证成功，初始化用户 UserSession
			UserSession session = new UserSession(u);
			setSessionAttr("userSession", session);
			redirect("/index");
		}else{
			setAttr("msg", "用户名不存在或者密码错误");
			setAttr("callback", callbackUrl);
			redirect("/security/login?msg=2");
		}
	}
	
	/**
	 * 登出
	 */
	public void logout(){
		removeSessionAttr("userSession");
		redirect("/security/login");
	}

}
